<template>
  <!-- 左侧栏 -->
  <div
    :class="sidebarOpen ? 'translate-x-0' : '-translate-x-full'"
    class="w-64 bg-[#f9fbff] border-r border-gray-200 fixed left-0 top-0 h-full transition-transform duration-300 ease-in-out z-10 overflow-y-auto"
  >
    <div class="p-0 h-full flex flex-col">
      <div class="flex items-center justify-center p-4 cursor-pointer" @click="jumpToIndexPage">
        <SvgIcon name="ai-robot-logo" customSvgCss="w-8 h-8 text-gray-700 mr-3" />
        <span class="text-2xl font-bold font-sans tracking-wide text-gray-800">小满AI机器人</span>
      </div>

      <!-- 开启新对话按钮 -->
      <button
        @click="jumpToIndexPage"
        class="mx-auto mb-[34px] my-2 px-6 py-2 text-white rounded-xl transition-colors new-chat-btn w-fit cursor-pointer"
      >
        <SvgIcon name="new-chat" customSvgCss="w-6 h-6 mr-1.5 inline text-[#4d6bfe]" />
        开启新对话
      </button>

      <!-- 历史对话区域 -->
      <div class="my-4 px-2 overflow-y-auto overflow-x-hidden flex-1">
        <div class="space-y-1">
          <div class="text-xs px-3 py-1 text-gray-500">历史对话</div>
          <div
            v-for="(value, index) in historyList"
            :key="index"
            class="relative px-3 py-1 rounded-xl hover:bg-[rgb(239,246,255)] cursor-pointer transition-colors flex items-cneter justify-between h-9"
            @mouseenter="showButton = value.uuid"
            @mouseleave="showButton = null"
            @click="jumpToChatPage(value.uuid)"
          >
            <a-tooltip placement="top">
              <template #title>
                <span>{{ value.summary }}</span>
              </template>
              <p class="text-[14px] text-gray-800 overflow-hidden whitespace-nowrap">
                <div v-if="changeNameRef.state && changeNameRef.uuid === value.uuid">
                  <a-input v-model:value="changedName" @keydown.enter="changeNameLeave"/>
                </div>
                <div v-else>
                  {{ value.summary }}
                </div>
              </p>
            </a-tooltip>
            <!-- 下拉菜单 -->
            <a-dropdown>
              <template #overlay>
                <a-menu>
                  <a-menu-item key="rename" @click="changeNameState(value.summary, value.uuid, value.id)"
                    ><EditOutlined />重命名</a-menu-item
                  >
                  <a-menu-item key="delete" danger @click="delChatFunc(value.uuid)"
                    ><DeleteOutlined /> 删除</a-menu-item
                  >
                </a-menu>
              </template>
              <!-- 右边菜单按钮 -->
              <button
                class="z-10 rounded-lg outline-none justify-center items-center bg-white w-6 h-6 flex absolute right-2 top-1/2 transform -translate-y-1/2 transition-all duration-300 hover:bg-gray-50"
                :style="{ opacity: (showButton = value.uuid ? 1 : 0) }"
              >
                <EllipsisOutlined class="w-4 h-4 text-gray-500" />
              </button>
            </a-dropdown>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 侧边栏切换按钮 -->
  <a-tooltip placement="bottom">
    <template #title>
      <span>{{ sidebarOpen ? '收缩侧边栏' : '打开侧边栏' }}</span>
    </template>

    <button
      :class="sidebarOpen ? 'left-64' : 'left-0'"
      @click="toggleSidebar"
      class="fixed top-4 z-20 bg-white border border-gray-200 rounded-r-lg p-2 transition-all duration-300"
    >
      <SvgIcon
        :name="sidebarOpen ? 'sidebar-open' : 'sidebar-close'"
        :customSvgCss="sidebarOpen ? 'w-6 h-6 text-gray-400' : 'w-7 h-7 text-gray-400'"
      />
    </button>
  </a-tooltip>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import SvgIcon from '@/components/SvgIcon.vue'
import { EllipsisOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { delChat, getHistoryChats, renameChat } from '@/api/request'
import { message } from 'ant-design-vue'

const router = useRouter()

const changeNameRef = ref({state: false, uuid: '', id: 0})

const jumpToIndexPage = () => {
  router.push({
    name: 'Index',
  })
}

const jumpToChatPage = (uuid) => {
  router.push({
    name: 'ChatPage',
    params: {
      chatId: uuid,
    },
  })
}

const props = defineProps({
  sidebarOpen: {
    type: Boolean,
    rquired: true,
  },
})

// 定义emits
const emit = defineEmits(['toggle-sidebar'])

// 切换侧边栏显示/隐藏
const toggleSidebar = () => {
  console.log('toggleSidebar')
  emit('toggle-sidebar')
}

const historyList = ref([
  { uuid: '1', summary: '对话1打卡简单看见啊活动空间啊浩丰科技哈佛流口水' },
  { uuid: '2', summary: '对话2' },
  { uuid: '3', summary: '对话3' },
  { uuid: '4', summary: '对话4' },
  { uuid: '5', summary: '对话5' },
  { uuid: '6', summary: '对话6' },
])

const showButton = ref(null)
const changedName = ref('')

onMounted(() => {
  getHistoryChats().then((res) => {
    if (res.data.success) {
      historyList.value = res.data.data
    }
  })
})

const delChatFunc = async (uuid: string) => {
  await delChat({ uuid }).then((res) => {
    if (res.data.success) {
      console.log('删除成功')
    }
  })
}

const changeNameState = (summary: string, uuid: string, id: number) => {
  changeNameRef.value = {state: true, uuid: uuid, id: id}

  changedName.value = summary
}

const changeNameLeave = (event) => {
  const value = event.target.value

  historyList.value.forEach(item => {
    if (item.uuid === changeNameRef.value.uuid) {
      item.summary = value
    }
  });

  renameChat({id: changeNameRef.value.id, summary: value}).then(res => {
    if (res.data.success) {
      message.success("重命名成功")
    }
  })

  changeNameRef.value.state = false
}
</script>

<style scoped>
.overflow-y-auto {
  scrollbar-color: rgba(0, 0, 0, 0.2) transparent;
}
.new-chat-btn {
  background-color: rgb(219, 234, 254);
  color: #4d6bfe;
}
.new-chat-btn:hover {
  background-color: #c6dcf8;
}
</style>
